package xdu.lz.stage6_threadpool.chapter3_threadPoolExecutorAPI;

import java.util.List;
import java.util.concurrent.*;

/**
 * Created at 2019/10/24 0024 上午 11:24
 * shutdown:
 * 把线程池状态设置为SHUTDOWN,拒绝接受任何任务,把当前任务和任务队列中
 * 的所有任务执行完毕后，关闭IDEL线程。
 *
 * shutdownNow：
 * 中断当前所有正在执行的线程，并把任务队列中的任务排干，直接返回，不再执行。
 *
 * isShutdown 来判断是否已经调用过shutdown
 * isTerminating 在shutdown调用后是true
 * isTerminated 会在线程池真正关闭后是true
 *
 *
 * {@link ThreadPoolExecutor#awaitTermination(long, TimeUnit)}
 * 最多等待long time,不然继续执行代码。
 */
public class ShutdownTest {


    public static void main(String[] args) {
        testShutdownNow();
    }

    /**
     * {@link ExecutorService#shutdownNow()}
     */
    private static void testShutdownNow(){
        ExecutorService service = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 5; i++) {
            service.submit(()->{
                try {
                    Thread.sleep(10_000);
                } catch (InterruptedException e) {
                    System.out.println("is interrupted");
                    e.printStackTrace();
                }
            });
        }

        List<Runnable> runnables = service.shutdownNow();
        // 4个task未被执行，在任务队列中被排干，返回
        // 正在执行的task被interrupt
        runnables.forEach(System.out::println);
    }
    /**
     *
     * {@link ThreadPoolExecutor#shutdown()}
     * {@link ThreadPoolExecutor#isShutdown()}
     * {@link ThreadPoolExecutor#isTerminated()}
     * {@link ThreadPoolExecutor#isTerminating()}
     */
    private static void isShutdown() throws ExecutionException, InterruptedException {
        ThreadPoolExecutor service = (ThreadPoolExecutor) Executors.newSingleThreadExecutor();

        service.execute(() -> {
            System.out.println("start");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("finished");
        });

        System.out.println("isShutdown = " + service.isShutdown());
        service.shutdown();
        // true
        System.out.println("isTerminated = " + service.isTerminated());
        System.out.println("isTerminating = " + service.isTerminating());

        Thread.sleep(1000);
        // the pool has been shutdown
        System.out.println("isShutdown = " + service.isShutdown());
        //shutdown调用后会拒绝再提交的任务

        service.execute(() -> {
            System.out.println("the task will be reject because the threadPool has been shutdown");
        });

    }
}
